import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.sun.deploy.security.JarSignature.load;
import static com.sun.deploy.util.SessionState.save;


class Message{
    public String form;
    public String to;
    public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();
    //此处把消息保存到内存中，（一旦重启服务器，数据就没了），更科学的是应该保存到数据库中
    //private List<Message> messageList = new ArrayList<>();不使用内存存储了

    //用来实现“存档”功能
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.读取情求的body，转换成Java对象
        Message message=objectMapper.readValue(req.getInputStream(),Message.class);
        //2.得到message之后，保存到服务器中
        //messageList.add(message);
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //3.返回响应（不太必要，返回一个200ok就行
        resp.setStatus(200);//resp.getWriter().writer("ok")
    }

    private void save(Message message) throws SQLException {
        //通过jdbc往数据库里存一个数据
        //1.创建数据源
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql:127.0.0.1:3306/learn java?character=utf8&&useSSL=false");
        //SSL就是HTTPS中的加密方案
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造SQL语句
        String sql = "insert into message values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,message.form);
        statement.setString(2,message.message);
        statement.setString(3,message.to);
        //4.执行SQL
        statement.executeUpdate();
        //5.释放资源，关闭连接
        statement.close();
        connection.close();
    }

    //用来实现“读档”功能
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //把内存中的这些message，组织成json格式，返回到响应中
        List<Message> messageList= null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String respJson= objectMapper.writeValueAsString(messageList);
        //这行代码非常关键，告诉浏览器，返回的响应的body是一个json格式（utf8编码）
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respJson);
    }

    private List<Message> load() throws SQLException {
        //通过jdbc往数据库里读出数据
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql:127.0.0.1:3306/learnjava?character=utf8&&useSSL=false");
        //SSL就是HTTPS中的加密方案
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造SQL语句
        String sql = "select *from message";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4.执行SQL
        ResultSet resultSet = statement.executeQuery();
        //5.遍历结果集合
        List<Message> messageList = new ArrayList<>();
        while (resultSet.next()){
            Message message = new Message();
            message.form = resultSet.getString("from");
            message.to= resultSet.getString("to");
            message.message=resultSet.getString("message");
            messageList.add(message);

        }
        //6.关闭连接释放资源
        resultSet.close();
        statement.close();
        connection.close();
        return messageList;
    }
}
